package org.openqa.selenium;

import cn.hutool.core.net.URLDecoder;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v129.network.Network;
import org.openqa.selenium.devtools.v129.network.model.Response;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Slf4j
public class WebDirverTester {

    @Test
    public void testWebDirver() throws Exception {
//        String url = "https://www.france24.com/en";
//        String url = "https://www.reuters.com/world/africa/";
//        String url = "https://www.browserscan.net/bot-detection";
//        String url = "https://twitter.com/GoitaAssimi";
        String url = "https://twitter.com/APS_Senegal";
        String responseBody = getWebDriverResponseBody(url);
        log.info("responseBody=>" + responseBody);
    }

    private String getWebDriverResponseBody(String url) {
        System.setProperty("webdriver.chrome.driver", "D:/chromedriver/chromedriver-129.0.6668.100.exe");
        WebDriver driver = null;
        try {
            ChromeOptions options = new ChromeOptions();
            options.setPageLoadStrategy(PageLoadStrategy.EAGER);
            // 只在Linux非root用户下需要
//            options.addArguments("--no-sandbox");
            // 如果需要无头模式
//            options.addArguments("--headless");
            options.addArguments("--remote-allow-origins=*");
            options.addArguments("blink-settings=imagesEnabled=false");
//            options.addArguments("--remote-debugging-port=9222");


//            // 获取DevTools实例
//            DevTools devTools = ((HasDevTools) driver).getDevTools();
//            devTools.createSession();
//
//            // 启用网络监听
//            devTools.send(Network.enable(true));
//
//            // 设置请求拦截
//            devTools.send(Network.setRequestInterceptionEnabled(true));
//
//            // 注册请求拦截处理器
//            ExecutorService executor = Executors.newSingleThreadExecutor();
//            devTools.addListener(Network.requestWillBeSent(), executor, requestEvent -> {
//                String url = requestEvent.getRequest().getUrl();
//                String mimeType = requestEvent.getRequest().getMIMEType();
//                InterceptionId interceptionId = requestEvent.getRequest().getInterceptionId();
//
//                // 只加载HTML资源
//                if (!mimeType.equals("text/html")) {
//                    devTools.send(Network.failInterceptedRequest(interceptionId, "Blocked by Selenium"));
//                } else {
//                    devTools.send(Network.continueInterceptedRequest(interceptionId));
//                }
//            });

            driver = new ChromeDriver(options);

            DevTools devTools = ((ChromeDriver) driver).getDevTools();
            devTools.createSession();

            // 注册监听网络请求的事件
            devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
            devTools.addListener(Network.requestWillBeSent(), request -> {
                System.out.println("Request intercepted: " + request.getRequest().getUrl());
            });

            devTools.addListener(Network.responseReceived(), response -> {
                Response res = response.getResponse();
                System.out.println("Response received: " + res.getStatus() + " - " + res.getUrl());
            });

            driver.get(url);

            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
            wait.until((ExpectedCondition<WebElement>) d -> d.findElement(By.tagName("article")));

            Actions actions = new Actions(driver);
            for (int i = 0; i < 50; i++) {
                actions.sendKeys(Keys.PAGE_DOWN).perform();
            }

            TimeUnit.SECONDS.sleep(20);

            String pageSource = driver.getPageSource();
            log.info("pageSource:[{}]", pageSource);
        } catch (Exception e) {
            log.error("请求网页异常, url:[{}]", url, e);
        } finally {
            log.info("关闭浏览器");
//            if (Objects.nonNull(driver)) {
//                driver.quit();
//            }
        }
        return "EMPTY";
    }

    @Test
    public void testDecode() throws Exception {
        List<String> articles = new ArrayList<>();
        articles.add("https://www.reuters.com/pf/api/v3/content/fetch/articles-by-section-alias-or-id-v1?query=%7B%22arc-site%22%3A%22reuters%22%2C%22fetch_type%22%3A%22collection%22%2C%22offset%22%3A20%2C%22section_id%22%3A%22%2Fworld%2Fafrica%2F%22%2C%22size%22%3A9%2C%22uri%22%3A%22%2Fworld%2Fafrica%2F%22%2C%22website%22%3A%22reuters%22%7D&d=219&_website=reuters");
        articles.add("https://www.reuters.com/pf/api/v3/content/fetch/articles-by-section-alias-or-id-v1?query=%7B%22arc-site%22%3A%22reuters%22%2C%22fetch_type%22%3A%22collection%22%2C%22offset%22%3A20%2C%22section_id%22%3A%22%2Fworld%2Fafrica%2F%22%2C%22size%22%3A9%2C%22uri%22%3A%22%2Fworld%2Fafrica%2F%22%2C%22website%22%3A%22reuters%22%7D&d=219&_website=reuters");
        articles.add("https://www.reuters.com/pf/api/v3/content/fetch/articles-by-section-alias-or-id-v1?query=%7B%22arc-site%22%3A%22reuters%22%2C%22fetch_type%22%3A%22collection%22%2C%22offset%22%3A38%2C%22section_id%22%3A%22%2Fworld%2Fafrica%2F%22%2C%22size%22%3A9%2C%22uri%22%3A%22%2Fworld%2Fafrica%2F%22%2C%22website%22%3A%22reuters%22%7D&d=219&_website=reuters");
        articles.add("https://www.reuters.com/pf/api/v3/content/fetch/articles-by-section-alias-or-id-v1?query=%7B%22arc-site%22%3A%22reuters%22%2C%22fetch_type%22%3A%22collection%22%2C%22offset%22%3A47%2C%22section_id%22%3A%22%2Fworld%2Fafrica%2F%22%2C%22size%22%3A9%2C%22uri%22%3A%22%2Fworld%2Fafrica%2F%22%2C%22website%22%3A%22reuters%22%7D&d=219&_website=reuters");
        articles.add("https://www.reuters.com/pf/api/v3/content/fetch/articles-by-section-alias-or-id-v1?query=%7B%22arc-site%22%3A%22reuters%22%2C%22fetch_type%22%3A%22collection%22%2C%22offset%22%3A56%2C%22section_id%22%3A%22%2Fworld%2Fafrica%2F%22%2C%22size%22%3A9%2C%22uri%22%3A%22%2Fworld%2Fafrica%2F%22%2C%22website%22%3A%22reuters%22%7D&d=219&_website=reuters");

        for (String article : articles) {
            log.info(URLDecoder.decode(article, StandardCharsets.UTF_8));
        }
    }

}
